package com.mingliqiye.minecraft.enchantment.conflict.fabric;

import static com.mingliqiye.minecraft.enchantment.conflict.common.NetWorkUtils.isLocalAddress;
import static net.minecraft.commands.Commands.literal;

import com.google.gson.Gson;
import com.mingliqiye.minecraft.enchantment.conflict.common.ConfigManager;
import com.mingliqiye.minecraft.enchantment.conflict.common.MinecraftMod;
import com.mingliqiye.minecraft.enchantment.conflict.common.VersionsEnum;
import com.mingliqiye.minecraft.enchantment.conflict.common.WebConfigCore;
import com.mingliqiye.minecraft.enchantment.conflict.common.enchantment.EnchantmentController;
import com.mingliqiye.minecraft.enchantment.conflict.fabric.network.ConfigPayload;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.ChatFormatting;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import net.minecraft.server.MinecraftServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FabricMod implements ModInitializer {

    public static final Logger LOGGER = LoggerFactory.getLogger(MinecraftMod.MOD_ID);
    public static MinecraftServer SERVER;
    public static final ConfigManager CONFIGMANAGER = new ConfigManager(
        FabricLoader.getInstance().getConfigDir(),
        LOGGER,
        VersionsEnum.V121
    );

    public static final WebConfigCore WEBCONFIGCORE = new WebConfigCore(
        CONFIGMANAGER,
        new FabricWebConfigCoreMeMethod()
    );
    public static final EnchantmentController ENCHANTMENTCONTROLLER = new EnchantmentController(CONFIGMANAGER);

    @Override
    public void onInitialize() {
        ConfigPayload.initializeServer();
        ServerLifecycleEvents.SERVER_STARTED.register((m) -> {
            SERVER = m;
            WEBCONFIGCORE.start();
        });
        ServerLifecycleEvents.SERVER_STOPPING.register((m) -> {
            WEBCONFIGCORE.stop();
        });
        CommandRegistrationCallback.EVENT.register((dispatcher, registryAccess, environment) -> {
            dispatcher.register(
                literal("enchantmentdoesnotconflict-config").executes((context) -> {
                        var source = context.getSource();
                        boolean isLocal =
                            source.getServer().isSingleplayer() ||
                            source.getEntity() == null ||
                            (source.getPlayer() != null &&
                                isLocalAddress(source.getPlayer().connection.getRemoteAddress()));
                        if (isLocal) {
                            WEBCONFIGCORE.openWeb();
                            source.sendSuccess(
                                () ->
                                    Component.literal("打开")
                                        .append(Component.literal(WEBCONFIGCORE.getLocalUrl()))
                                        .withStyle(
                                            Style.EMPTY.withColor(ChatFormatting.BLUE).withUnderlined(true) // 蓝色带下划线
                                        )
                                        .append(Component.literal("成功"))
                                        .withStyle(ChatFormatting.GREEN),
                                true
                            );
                        } else {
                            source.sendFailure(
                                Component.literal("请使用服务器所在的机器执行该命令").withStyle(ChatFormatting.RED)
                            );
                        }
                        return 1;
                    })
            );
        });
    }
}
